package com.iw.core.security.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.iw.adoms.entity.Department;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import com.iw.core.orm.PageData;
import com.iw.core.security.MySecurityMetadataSource;
import com.iw.core.security.entity.Resources;
import com.iw.core.security.entity.ResourcesGroup;
import com.iw.core.security.entity.Roles;
import com.iw.core.security.service.ResourcesGroupService;
import com.iw.core.security.service.ResourcesService;
import com.iw.core.security.service.RolesService;
import com.iw.core.utils.WebUtils;

@Controller
@RequestMapping("/security/roles")
public class RolesAction {
	@Resource
	private RolesService rolesService;

	@Resource
	private ResourcesService resourcesService;

	@Resource
	private ResourcesGroupService resourcesGroupService;

	@Resource
	private MySecurityMetadataSource mySource;

	@RequestMapping("/list")
	public ModelMap list(HttpServletRequest request) {
		PageData<Roles> pageData = new PageData<Roles>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		pageData = rolesService.find(pageData);

		return new ModelMap(pageData);
	}

	@RequestMapping(value = "/new")
	public String addForm(Model model) {
		List<ResourcesGroup> groupList = resourcesGroupService.findAll();
		Map<Object, Object> groupResources = new LinkedHashMap<Object, Object>();
		List<Resources> resourcesList = resourcesService.findAll();
		for (ResourcesGroup group : groupList) {
			List<Object> list = new ArrayList<Object>();
			for (Resources resources : resourcesList) {
				if (resources.getGroup().getName().equals(group.getName())) {
					list.add(resources);
				}
			}
			groupResources.put(group, list);
		}
		model.addAttribute("groupResources", groupResources);
		return "/security/roles/input";
	}

	@RequestMapping(value = "/edit/{id}")
	public String editForm(@PathVariable("id") Integer id, Model model) {
		Roles roles = rolesService.find(id);
		model.addAttribute(roles);
		List<ResourcesGroup> groupList = resourcesGroupService.findAll();
		Map<Object, Object> groupResources = new LinkedHashMap<Object, Object>();
		List<Resources> resourcesList = resourcesService.findAll();
		for (ResourcesGroup group : groupList) {
			List<Object> list = new ArrayList<Object>();
			for (Resources resources : resourcesList) {
				if (resources.getGroup().getName().equals(group.getName())) {
					list.add(resources);
				}
			}
			groupResources.put(group, list);
		}
		model.addAttribute("groupResources", groupResources);
		return "/security/roles/input";
	}


    @RequestMapping(value = "/repeat")
    @ResponseBody
    public boolean repeat(String value, Integer id, String property) {
        try {
            List<Roles> departments = rolesService.findList(property, value);
            if (departments != null && departments.size() > 0) {
                if (id != 0) {
                    Roles d = rolesService.find(id);
                    if (property.equals("name") && !d.getName().equals(value)) {
                        return false;
                    } else if (property.equals("type") && !d.getType().equals(value)) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Roles roles, HttpServletRequest request) {
		String[] resourcesIds = request.getParameterValues("resources.id");
		if (resourcesIds != null) {
			Set<Resources> resourcesSet = new HashSet<Resources>();
			for (String resourcesId : resourcesIds) {
				try {
					Resources resources = resourcesService.find(Integer.parseInt(resourcesId));
					resourcesSet.add(resources);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			roles.setResources(resourcesSet);
		}
		if (roles.isNew()) {
			rolesService.save(roles);
		} else {
			rolesService.update(roles);
		}

		// 重新加载权限
		mySource.loadResourcesDefine();
		return "redirect:/security/roles/list";// 重定向
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") Integer id) {
		rolesService.delete(id);
		return "redirect:/security/roles/list";// 重定向
	}

	@RequestMapping(value = "/visible/{id}")
	public String visible(@PathVariable("id") Integer id) {
		rolesService.visible(id);
		return "redirect:/security/roles/list";// 重定向
	}

	@RequestMapping(value = "/unVisible/{id}")
	public String unVisible(@PathVariable("id") Integer id) {
		rolesService.unVisible(id);
		return "redirect:/security/roles/list";// 重定向
	}

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
	}

}
